package com.fourforfo.fourmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.fourforfo.common.utils.R;
import com.fourforfo.fourmall.product.config.MyThreadConfig;
import com.fourforfo.fourmall.product.entity.SkuImagesEntity;
import com.fourforfo.fourmall.product.entity.SpuInfoDescEntity;
import com.fourforfo.fourmall.product.entity.SpuInfoEntity;
import com.fourforfo.fourmall.product.feign.SeckillFeignService;
import com.fourforfo.fourmall.product.service.*;
import com.fourforfo.fourmall.product.to.SeckillSkuRedisTO;
import com.fourforfo.fourmall.product.vo.ProductItemVO;
import com.fourforfo.fourmall.product.vo.spu.Skus;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourforfo.common.utils.PageUtils;
import com.fourforfo.common.utils.Query;

import com.fourforfo.fourmall.product.dao.SkuInfoDao;
import com.fourforfo.fourmall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService imagesService;

    @Autowired
    SpuInfoService spuInfoService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    SeckillFeignService seckillFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 获取商品详情页skuItem
     * @return
     */
    /*
    1.获取sku的基本信息	(假如花费) 0.5s
    2.获取sku的图片信息	0.5s
    3.获取sku的促销信息	1s
    4.获取spu的所有销售属性	1s
    5.获取规格参数组及组下的规格参数	1s
    6.获取sku的秒杀信息 1s
    6.spu详情	1s
     */
    @Override
    public ProductItemVO getProductItem(Long skuId) {

//        Long startTime = System.currentTimeMillis();


        ProductItemVO productItemVO = new ProductItemVO();
        if(skuId==null||skuId==0L){
            return productItemVO;
        }
//        1.获取sku的基本信息  pms_sku_info
////        SkuInfoEntity skuInfo;
//        new QueryWrapper<SkuInfoEntity>().eq("sku_id",skuId));
        CompletableFuture<SkuInfoEntity> infoAsync = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = baseMapper.selectById(skuId);
            productItemVO.setSkuInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);


//        2.获取sku的图片信息 pms_sku_images
//        List<SkuImagesEntity> skuImages;
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> imagesEntities = imagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            productItemVO.setSkuImages(imagesEntities);
        }, executor);

//        3.获取spu的介绍图片信息 pms_spu_info_desc
//        SpuInfoDescEntity spuInfoDesc;
        CompletableFuture<Void> descFuture = infoAsync.thenAcceptAsync((skuInfoEntity) -> {
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(skuInfoEntity.getSpuId());
            productItemVO.setSpuInfoDesc(spuInfoDescEntity);
        }, executor);

//        4.获取spu的所有销售属性	1s
//        List<ProductItemVO.SkuItemSaleAttrsVO> skuAttrs;
        CompletableFuture<Void> saleAttrFuture = infoAsync.thenAcceptAsync((skuInfoEntity) -> {
            List<ProductItemVO.SkuItemSaleAttrsVO> skuAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(skuInfoEntity.getSpuId());
            productItemVO.setSkuAttrs(skuAttrs);
        }, executor);

//        5.获取Spu规格参数组及组下的规格参数	1s
//        List<ProductItemVO.SpuItemBaseAttrVO> spuAttrs;

        //6.获取sku是否参与秒杀优惠

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if(r.getCode()==0){
                SeckillSkuRedisTO skuRedisTO = r.getData(new TypeReference<SeckillSkuRedisTO>() {
                });
                productItemVO.setSeckillSku(skuRedisTO);
            }
        },executor);



        CompletableFuture<Void> baseAttrFuture = infoAsync.thenAcceptAsync((skuInfoEntity) -> {
            List<ProductItemVO.SpuItemBaseAttrVO> attrGroupVOs = attrGroupService.getAttrGroupWithAttrsBySpuId(skuInfoEntity.getSpuId());
            productItemVO.setAttrGroups(attrGroupVOs);
        }, executor);

        try {
            CompletableFuture.allOf(seckillFuture,saleAttrFuture,descFuture,baseAttrFuture,imagesFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

//        System.out.println("优化后整个查询商品详情所花费时间为："+(System.currentTimeMillis()-startTime)+"ms");
        return productItemVO;
    }


    /**
     * 关键字：key ，catelogId， brandId， min和max（价格区间）；
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper();

        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String min = (String) params.get("min");
        String max = (String) params.get("max");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(wrapper->{
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        if(!StringUtils.isEmpty(catelogId)&&!"0".equals(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        if(!StringUtils.isEmpty(brandId)&&!"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        if(!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",min);
        }
        if(!StringUtils.isEmpty(max) && !"0".equals(max)){
            queryWrapper.le("price",max);
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }



    /**
     * sku的基本信息 pms_sku_info
     * @param skuInfoEntity
     */
    @Override
    public void saveSkusInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    /**
     * 1. 查出当前的spuId对应的所有sku信息
     * @param spuId
     */
    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntitys = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntitys;
    }

    @Override
    public Map<Long, Map<Long, SkuInfoEntity>> listSkuInfoBySkuIdGroupBySessionId(Map<Long, List<Long>> idMaps) {
        Map<Long, Map<Long, SkuInfoEntity>> mapMap = new HashMap<>();
        Set<Long> sessionIds = idMaps.keySet();
        for (Long sessionId : sessionIds) {
            List<Long> skuIds = idMaps.get(sessionId);
            List<SkuInfoEntity> skuInfoEntities = this.listByIds(skuIds);
            //将上一行的skuInfoEntities封装成map格式
            Map<Long, SkuInfoEntity> skuInfoEntityMap = skuInfoEntities.stream()
                                                        .collect(Collectors.toMap(SkuInfoEntity::getSkuId,
                                                                Function.identity()));
            mapMap.put(sessionId,skuInfoEntityMap);
        }
        return mapMap;
    }

}